package com.vvv.designpattern.asyncpattern;

import java.util.LinkedList;

/**
 * @author vvv
 * @date 2023-10-15 16 54
 * discription
 */
public class ConsumerAndProvider {
    public static void main(String[] args) {
        MessageQueue messageQueue = new MessageQueue(2);
        for (int i = 0; i < 3; i++) {
            int id = i;
            new Thread(() -> {
                messageQueue.put(new Message(id, "值" + id));
            }, "生产者" + i).start();
        }
        new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                Message take = messageQueue.take();
            }
        }, "消费者").start();
    }
}
class MessageQueue {
    private LinkedList<Message> list = new LinkedList<>();
    private int capacity;

    public MessageQueue(int capacity) {
        this.capacity = capacity;
    }

    public Message take() {
        synchronized (list) {
            Thread thread = Thread.currentThread();
            while (list.isEmpty()) {
                System.out.println(thread.getId() + "消息队列中没有消息消费，消费者等待");
                try {
                    list.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            Message message = list.removeFirst();
            System.out.println(thread.getId() + " 消费者消费了一条消息");
            // 通知生产者
            list.notify();
            return message;
        }
    }

    public void put(Message message) {
        synchronized (list) {
            Thread thread = Thread.currentThread();
            while (list.size() == capacity) {
                System.out.println(thread.getId() + " 队列已满，生产者等待");
                try {
                    list.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            list.addLast(message);
            System.out.println(thread.getId() + "已生产消息: " + message);
            // 通知消费者
            list.notify();
        }
    }

}
class Message {
    private long id;
    private Object message;

    public Message(long id, Object message) {
        this.id = id;
        this.message = message;
    }

    public long getId() {
        return id;
    }

    public Object getMessage() {
        return message;
    }

    @Override
    public String toString() {
        return "Message{" +
                "id=" + id +
                ", message=" + message +
                '}';
    }
}
